<template>
  <div class="container">

    <el-card>
      <el-button type="primary" :loading="exportLoading" @click="onExcelExport">
        导出excel
      </el-button>
      <el-button type="primary" @click="onAddEmployee">
        新增员工
      </el-button>
    </el-card>

    <el-card class="table-wrapper">
      <my-table :table-props="{
        data: employeeList.rows,
        border: true
      }" :columns="[
          { label: '序号', prop: 'index', width: 50, align: 'center' },
          { label: '姓名', prop: 'username', width: 100, align: 'center' },
          { label: '头像', slotName: 'avatar', align: 'center' }, // 带插槽
          { label: '手机号', prop: 'mobile', width: 150, align: 'center' },
          { label: '工号', prop: 'workNumber', width: 80, align: 'center' },
          { label: '聘用形式', prop: 'formOfEmployment', width: 80, align: 'center' },
          { label: '部门', prop: 'departmentName', width: 150, align: 'center' },
          { label: '入职时间', prop: 'timeOfEntry', width: 150, align: 'center' },
          { label: '状态', slotName: 'status', align: 'center' }, // 带插槽
          { label: '操作', slotName: 'operators', width: 300, align: 'center', fixed: 'right' }, // 带插槽
        ]" :pagination-props="{
          layout: 'total, pager',
          total: employeeList.total
        }" :pagination-events="events">
        <template #avatar>
          <div class="avatar">
            <img
              src="https://img1.baidu.com/it/u=1960292808,1761809160&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1659978000&t=89036a315babc710e9016507ea96680b"
              alt="">
          </div>
        </template>
        <template #status>
          <el-switch value />
        </template>
        <template v-slot:operators="scope">
          <el-button type="text" size="small" @click="onRowClick(scope.row)">查看</el-button>
          <el-button type="text" size="small" @click="onRowClick(scope.row)">转正</el-button>
          <el-button type="text" size="small" @click="onRowClick(scope.row)">调岗</el-button>
          <el-button type="text" size="small" @click="onRowClick(scope.row)">离职</el-button>
          <el-button type="text" size="small" @click="onRoleClick(scope.row)">角色</el-button>
          <el-button type="text" size="small" @click="onRowClick(scope.row)">删除</el-button>
        </template>
      </my-table>
    </el-card>

    <!-- 角色详情弹窗 -->
    <el-dialog title="分配角色" :visible.sync="roleDetailVisible" width="400px" @close="onRoleDetailClose">
      <el-checkbox-group v-model="roleDetailCheckList">
        <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">
          {{ role.name }}
        </el-checkbox>
      </el-checkbox-group>

      <span slot="footer" class="dialog-footer">
        <el-button @click="onRoleDetailClose">取消</el-button>
        <el-button type="primary" @click="onRoleDetailOk">确定</el-button>
      </span>
    </el-dialog>

    <!-- 新增员工弹窗 -->
    <el-dialog title="新增员工" :visible.sync="addEmployeeVisible" width="600px" class="add-employee"
      @close="onAddEmployeeClose">

      <el-form ref="addEmployeeForm" :model="addEmployeeParams" status-icon :rules="addEmployeeRules"
        label-width="100px">

        <el-form-item label="姓名" prop="username">
          <el-input v-model="addEmployeeParams.username" type="text" autocomplete="off" />
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addEmployeeParams.mobile" type="text" autocomplete="off" />
        </el-form-item>

        <el-form-item label="入职时间" prop="timeOfEntry">
          <el-date-picker v-model="addEmployeeParams.timeOfEntry" type="date" placeholder="选择日期" format="yyyy-MM-dd" />
        </el-form-item>

        <el-form-item label="聘用形式" prop="formOfEmployment">
          <el-select v-model="addEmployeeParams.formOfEmployment" placeholder="请选择聘用形式">
            <el-option key="1" value="1" label="正式" />
            <el-option key="2" value="2" label="非正式" />
          </el-select>
        </el-form-item>

        <el-form-item label="工号" prop="workNumber">
          <el-input v-model="addEmployeeParams.workNumber" type="text" autocomplete="off" />
        </el-form-item>

        <el-form-item label="部门" prop="departmentName">
          <el-input type="text" :value="addEmployeeParams.departmentName" autocomplete="off"
            @click.native="showDepartmentTree" />
          <el-tree v-show="departmentTreeVisible" :data="departmentTree" :props="{
            children: 'children',
            label: 'name'
          }" default-expand-all @node-click="onDepartmentTreeNodeClick" />
        </el-form-item>

        <el-form-item label="转正时间" prop="correctionTime">
          <el-date-picker v-model="addEmployeeParams.correctionTime" type="date" placeholder="选择日期"
            format="yyyy-MM-dd" />
        </el-form-item>

      </el-form>

      <footer>
        <el-button type="primary" @click="onAddEmployeeOk">确定</el-button>
        <el-button @click="onAddEmployeeClose">取消</el-button>
      </footer>

    </el-dialog>

  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex'
import * as roleApi from '@/api/role'
import * as employeeApi from '@/api/employee'
import ExcelJS from 'exceljs'

let currentId = null

export default {
  name: 'Employee',
  data() {
    const validateMobile = (rule, value, callback) => {
      const telReg = /^1[3-9]\d{9}$/
      if (!telReg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validateNull = (rule, value, callback) => {
      console.log(value)
      if (!value.trim()) {
        callback(new Error(this.$t('值不能为空')))
      } else {
        callback()
      }
    }
    const validateDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('时间不能为空')))
      } else {
        callback()
      }
    }
    return {
      currentPage: 1,
      pageSize: 10,
      events: {
        'current-change': this.onCurrentPageChange
      },
      roleDetailVisible: false,
      roleDetailCheckList: [],
      // 是否弹出新增员工
      addEmployeeVisible: false,
      // 新增员工表单值
      addEmployeeParams: {
        username: '张三',
        mobile: '13012341234',
        timeOfEntry: '2020-11-11',
        formOfEmployment: '1',
        workNumber: '99999',
        departmentName: '总裁办',
        correctionTime: '2020-11-11'
      },
      // 新增员工校验规则
      addEmployeeRules: {
        username: [{ required: true, trigger: 'blur', validator: validateNull }],
        mobile: [{ required: true, trigger: 'blur', validator: validateMobile }],
        timeOfEntry: [{ required: true, trigger: 'blur', validator: validateDate }],
        formOfEmployment: [{ required: true, trigger: 'blur', validator: validateNull }],
        workNumber: [{ required: true, trigger: 'blur', validator: validateNull }],
        departmentName: [{ required: true, validator: validateNull }],
        correctionTime: [{ required: true, trigger: 'blur', validator: validateDate }]
      },
      departmentTreeVisible: false,
      // 导出按钮是否在加载中
      exportLoading: false
    }
  },
  computed: {
    ...mapState('employee', [
      'employeeList'
    ]),
    ...mapGetters('department', [
      'departmentTree'
    ]),
    ...mapState('role', [
      'roleList',
      'roleDetail'
    ])
  },
  methods: {
    ...mapActions('employee', [
      'updateEmployeeList'
    ]),
    ...mapActions('department', [
      'updateDepartmentList'
    ]),
    ...mapActions('role', [
      'updateRoleList',
      'updateRoleDetail'
    ]),
    // 当前页改变时
    onCurrentPageChange(currentPage) {
      this.currentPage = currentPage
      this.updateEmployeeList({
        page: this.currentPage,
        size: this.pageSize
      })
    },
    async onRoleClick(row) {
      this.roleDetailVisible = true
      await this.updateRoleDetail(row.id)
      // 返显
      this.roleDetailCheckList = this.roleDetail.roleIds
      currentId = row.id
    },
    onRoleDetailClose() {
      this.roleDetailCheckList = []
      this.roleDetailVisible = false
    },
    onRoleDetailOk() {
      console.log(this.roleDetailCheckList)
      roleApi.updateRoleDetail(currentId, this.roleDetailCheckList)
      this.onRoleDetailClose()
    },
    onRowClick(row) {
      console.log(row)
    },
    // 新增员工
    onAddEmployee() {
      this.addEmployeeVisible = true
    },
    // 关闭新增员工弹窗
    onAddEmployeeClose() {
      this.addEmployeeVisible = false
      this.onAddEmployeeReset()
    },
    onAddEmployeeReset() {
      this.$refs.addEmployeeForm.resetFields()
      this.departmentTreeVisible = false
    },
    // 新增员工确认
    onAddEmployeeOk() {
      this.$refs.addEmployeeForm.validate(async (valid) => {
        if (valid) {
          await employeeApi.addEmployee(this.addEmployeeParams)
            .then(msg => this.$message.success(msg))
            .catch(msg => this.$message.error(msg))

          // 请求完成后关闭窗口
          this.onAddEmployeeClose()
          // 请求完成后刷新列表
          this.updateEmployeeList({
            page: this.currentPage,
            size: this.pageSize
          })
        } else {
          this.$message.error('请输入正确的表单信息')
          return false
        }
      })
    },
    onDepartmentTreeNodeClick(data) {
      this.addEmployeeParams.departmentName = data.name
      this.departmentTreeVisible = false
    },
    showDepartmentTree() {
      this.departmentTreeVisible = true
    },
    async onExcelExport() {
      this.exportLoading = true
      const employeeList = await employeeApi.getAllEmployeeList()

      // 导出excel
      const workbook = new ExcelJS.Workbook()
      const sheet = workbook.addWorksheet('Sheet1')
      // const rows = [
      //   ['序号', '姓名', '手机号', '工号', '聘用形式', '部门', '入职时间'],
      //   ...employeeList.rows.map(r => [
      //     r.index,
      //     r.username,
      //     r.mobile,
      //     r.workNumber,
      //     r.formOfEmployment,
      //     r.departmentName,
      //     r.timeOfEntry
      //   ])
      // ]
      // 定义表头
      sheet.columns = [
        { header: '序号', key: 'index', width: 50 },
        { header: '姓名', key: 'username', width: 100 },
        { header: '手机号', key: 'mobile', width: 150 },
        { header: '工号', key: 'workNumber', width: 80 },
        { header: '聘用形式', key: 'formOfEmployment', width: 80 },
        { header: '部门', key: 'departmentName', width: 150 },
        { header: '入职时间', key: 'timeOfEntry', width: 150 }
      ]
      sheet.addRows(employeeList.rows)
      const buffer = await workbook.xlsx.writeBuffer()

      // 用来把一大堆数字变成文件的东西
      const blob = new Blob([buffer])

      const fileName = `嘿嘿.xlsx`
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = fileName
      link.click()
      window.URL.revokeObjectURL(link.href)
      link.remove()

      this.exportLoading = false
    }
  },
  created() {
    this.updateRoleList()
    this.updateDepartmentList()
    this.updateEmployeeList({
      page: this.currentPage,
      size: this.pageSize
    })
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/common.scss";

.container {
  @include avatar(20px);
  padding: 16px;

  .avatar {
    display: inline-block;
  }

  .table-wrapper {
    margin-top: 16px;

  }
}

.add-employee {
  footer {
    display: flex;
    justify-content: center;
  }
}
</style>
